/**
 *@ClassName table-list
 *@Description  数据表的业务处理js文件
 *@Author JiJiang
 *@Date 2023/7/9 13:31
 *@Version 1.0
 */





var appTableList;

$(function () {


    //region 测试代码

    // //查询所有的数据库
    // $.get("/creator/database/list", function (data) {
    //     console.log("【数据库】请求的数据为：", data);
    // });
    //
    //
    // //查询所有的数据表
    // $.get("/creator/database/list/table", function (data) {
    //     console.log("【表】请求的数据为：", data);
    // });
    //
    // //查询所有的数据字段
    // $.get("/creator/database/list/column", function (data) {
    //     console.log("【字段】请求的数据为：", data);
    // });
    //endregion


    appTableList = new Vue({
        el: "#app-table-list"
        , data() {
            return {

                showTypeName: null,
                //代码生成的编辑回显数据
                codeGenEditData: {

                    info: {
                        tableName: null,
                        tableComment: null,
                        className: null,
                        functionAuthor: null,
                        remark: null
                    },
                    rows: null,
                    tables: null,


                },

                //代码预览参数
                codePreviewParam: {

                    showContent: "",
                    showFileType: "",
                },

                //代码预览数据对象
                previewData: {
                    sql: null,
                    domain: null,
                    mapperXml: null,
                    mapper: null,
                    service: null,
                    serviceImpl: null,
                    controller: null,
                    apiJs: null,
                    vueIndex: null,
                },

                //数据库表字段分页对象
                tableColumnPagination: {
                    //数据库表字段列表
                    list: [],
                },
                //是否显示数据表的结构信息
                showTableStructInfo: false,


                //数据库选项
                databaseOptions: [],
                //被选择的导入地数据表的全名 格式：数据库名+","+数据表名
                selectTableFullNames: [],
                //数据库表的列表
                tableList: [1, 2, 3, 4, 5],


                //数据库表列表查询对象
                tableQueryParam: {
                    tableSchema: null,
                    tableName: null,
                    page: 1,
                    limit: 10,
                },

                //数据表分页对象
                tablePagination: {
                    //总条数
                    totalCount: 0,
                    //总页数
                    totalPage: 0,
                    //页数列表
                    pageNumList: [],
                    //列表数据
                    list: [],
                },


                //弹窗标题
                title: "导入数据库表格",

                //选择的生成的表单id
                selectGenTableIds: [],


                //生成的数据表的分页查询对象
                genTablePaginationQueryParam: {
                    page: 1,
                    limit: 10,
                },
                //生成数据表的分页对象
                genTablePagination: {
                    //总条数
                    totalCount: 0,
                    //总页数
                    totalPage: 0,
                    //页数列表
                    pageNumList: [],
                    //列表数据
                    list: [],
                }
            }
        }
        , methods: {

            //确认修改
            confirmUpdate() {


                let toUpdateData = this.codeGenEditData.info;


                console.log("确认编辑的数据对象为：", toUpdateData);


                putRequest(`/creator/gen`, toUpdateData, undefined, true);

                //隐藏编辑回显弹出框
                $('#editModal').modal('hide');


            },


            //编辑回显类型按键点击事件
            editTypeBtnOnClick(typeName = "") {
                console.log("编辑回显内容类型被点击！", typeName);
                this.showTypeName = typeName;
                console.log('this.showTypeName ==', this.showTypeName);
            },

            //复制代码
            copyPreviewContent() {

                //region 使用Windows对象
                let val = document.getElementById('codeCopyContent');
                window.getSelection().selectAllChildren(val);
                document.execCommand("Copy")
                //endregion

            },


            //代码预览类型点击事件
            codePreviewTypeOnClick(fileType = "") {

                this.codePreviewParam.showContent = this.previewData[`${fileType}`]

                this.codePreviewParam.showFileType = fileType;

            },

            //编辑按键点击事件
            handleEdit(item = {}) {


                this.title = "编辑代码生成";
                let tableId = item.tableId;


                let responseData = getRequest(`/creator/gen/${tableId}`);


                if (responseData.status == 200) {
                    console.log(`ID为：${tableId} 表名为：${item.tableName}的编辑回显数据为：`, responseData);
                    this.codeGenEditData = responseData.data;
                    console.log("codeGenEditData ==", this.codeGenEditData);
                    this.showTypeName = 'info'
                }


            },

            //预览生成的代码
            handlePreview(item = {}) {


                this.title = "生成代码预览";
                let tableId = item.tableId;


                let responseData = getRequest(`/creator/gen/preview/${tableId}`);

                // console.log(`ID为：${tableId} 表名为：${item.tableName}的预览数据为：`, responseData);


                if (200 === responseData.status) {

                    let data = responseData.data;

                    //将值赋值给对应属性
                    this.previewData.controller = data[`vm/java/controller.java.vm`];

                    this.previewData.domain = data[`vm/java/domain.java.vm`];

                    this.previewData.mapper = data[`vm/java/mapper.java.vm`];

                    this.previewData.service = data[`vm/java/service.java.vm`];

                    this.previewData.serviceImpl = data[`vm/java/serviceImpl.java.vm`];

                    this.previewData.apiJs = data[`vm/js/api.js.vm`];

                    this.previewData.sql = data[`vm/sql/sql.vm`];

                    this.previewData.vueIndex = data[`vm/vue/index.vue.vm`];

                    this.previewData.mapperXml = data[`vm/xml/mapper.xml.vm`];


                    // console.log("previewData", this.previewData);
                    //
                    //
                    // console.log("previewData.domain", this.previewData.domain);

                    this.codePreviewParam.showContent = this.previewData.domain;

                    this.codePreviewParam.showFileType = 'domain'

                }


            },

            //生成代码操作
            handleGen(item = {}) {

                let tableName = item.tableName;
                let genType = item.genType;

                if (genType == '1') {
                    getRequest(`/creator/gen/genCode/${tableName}`);
                } else if (genType == '0') {
                    window.location.href = `/creator/gen/download/${tableName}`
                } else {

                }


            },

            //批量生成代码
            genTables() {


                let selectTableIds = this.selectGenTableIds;


                if (selectTableIds === null || selectTableIds.length < 1) {

                    return alert("请选择需要生成代码的表实体");
                }


                let selectGenTableNames = [];


                let genTableList = this.genTablePagination.list;


                genTableList.forEach((item) => {


                    //如果被选择了
                    if (selectTableIds.includes(item.tableId)) {
                        //添加名字
                        selectGenTableNames.push(item.tableName);
                    }


                });


                console.log("待生成的数据表名字为：", selectGenTableNames.join(","));


                let params = {
                    tables: selectGenTableNames.join(","),
                };

                // getRequest(`/creator/gen/batchGenCode`, params, undefined);

                window.location.href = `/creator/gen/batchGenCode?tables=${selectGenTableNames.join(",")}`


            },

            //同步生成数据库表
            syncGenTableStruct(item = {}) {

                let tableId = item.tableId;

                if (confirm(`确认同步ID为：${tableId},表名为：${item.tableName}的数据生成表？`)) {
                    putRequest(`/creator/gen/synchDb/${tableId}`, undefined, undefined, undefined);
                }


            },

            //删除选择的生成数据表
            handleDelete(item = {}) {


                if (item === null || item === undefined) {
                    return;
                }

                if (window.confirm(`确认删除ID为：${item.tableName}    表名为：${item.tableId}的生成数据表吗？`)) {

                    //删除数据
                    deleteRequest(`/creator/gen/${item.tableId}`);

                    //刷新列表
                    this.getGenTableList();

                }
            },

            //删除选中的所有生成的数据表
            deleteSelectGenTables() {


                let tableIds = this.selectGenTableIds;

                if (tableIds === null || tableIds.length < 1) {

                    alert("请选择需要被删除的数据表");
                    return;
                }

                if (window.confirm(`确认删除ID为：${JSON.stringify(tableIds)}  的生成数据表吗？`)) {

                    //删除数据
                    deleteRequest(`/creator/gen/${tableIds}`);

                    //刷新列表
                    this.getGenTableList();

                }


            },

            //管理数据表的结构显示
            closeTableStructShow() {
                this.showTableStructInfo = false;
            },

            //显示数据表的结构
            showTableStruct(item = {}) {


                console.log("被点击的表对象为：", item);
                this.showTableStructInfo = true;


                let columnsQueryParam = {

                    tableName: item.tableName,
                    tableSchema: item.tableSchema,

                };
                let responseData = getRequest(`/creator/database/list/column`, columnsQueryParam, undefined);

                console.log(`数据表：${item.tableName} 的字段列表为：`, responseData);

                this.tableColumnPagination.list = responseData.data;

            },
            //确认导入
            confirmImport() {


                let names = this.selectTableFullNames;

                console.log("确认导入的数据表全名列表 ===", this.selectTableFullNames);

                if (names == null || names.length < 1) {
                    alert("请选择需要导入的数据表");
                    return;
                }

                postRequest(`/creator/gen/importTable`, {tables: names.join(",")}, undefined, undefined);


            },
            //重置数据表列表查询
            resetTableListQuery(e) {


                this.tableQueryParam = {
                    tableSchema: null,
                    tableName: null,
                    page: 1,
                    limit: 10,
                };

                this.handleTableListQuery();
            },


            /**
             * 数据表分页按键点击
             */
            tablePaginationOnClick(flag = '') {
                let curPage = this.tableQueryParam.page;

                let totalPage = this.tablePagination.totalPage;

                if ('p' == flag) {
                    curPage = Math.max(1, curPage - 1);
                } else if ('n' == flag) {
                    curPage = Math.min(totalPage, curPage + 1);
                } else {
                    curPage = flag
                }
                this.tableQueryParam.page = curPage;
                console.log("【数据表列表】被点击的分页元素为 ======", flag);
                console.log("【数据表列表】被点击的分页元素为：", this.tableQueryParam.page);

                this.handleTableListQuery()

            },

            //处理数据数据表的查询
            handleTableListQuery() {
                let tableListQuery = this.tableQueryParam;

                // console.log("列表查询按键 【数据列表】参数查询对象为：", tableListQuery);
                let responseData = getRequest(`/creator/database/list/table`, tableListQuery, undefined);
                //如果请求成功
                if (200 === responseData.status) {
                    // this.tableList = responseData.data;
                    this.tablePagination.list = responseData.data;

                    //总条数
                    let totalCount = responseData.count;
                    this.tablePagination.totalCount = totalCount;


                    let limit = tableListQuery.limit;
                    let totalPage = Math.ceil(totalCount/limit);
                    this.tablePagination.totalPage = totalPage;



                    //region 计算页数列表


                    //当前页数
                    let currentPage = tableListQuery.page;


                    let startPage = 1, endPage = totalPage;


                    //如果总页数大于10
                    if (totalPage > 10) {
                        startPage = currentPage - 5 < 0 ? 1 : (currentPage - 4);
                        endPage = startPage + 9 > totalPage ? totalPage : (startPage + 9)


                        let offset = endPage - startPage;
                        if (offset != 9) {
                            startPage = endPage - 9;
                        }
                    }


                    let pageNumList = [];
                    for (let i = startPage; i <= endPage; i++) {
                        pageNumList.push(i);
                    }
                    this.tablePagination.pageNumList = pageNumList;
                    //endregion


                }

            },

            //数据库选项变化事件
            databaseSelectOnChange(e) {
                // console.log("e ====", e);


                this.tableQueryParam.page = 1;

                this.handleTableListQuery();

            },

            //数据表的父级checkbox被点击
            tableParentCheckboxOnClick(e) {

                let that = this;
                //如果被选中
                if (e.target.checked) {
                    let tableFullName = null;

                    that.tableList.forEach((item) => {
                        // console.log("item ===", item);
                        tableFullName = item.tableSchema + "." + item.tableName;
                        that.selectTableFullNames.push(tableFullName);
                    });
                    return;
                }
                //清空选择的数据表id
                that.selectTableFullNames = [];
            },
            //处理导入功能
            handleImport() {


                let responseData = null;

                //region 获取数据库的列表
                let dbQueryParam = {};

                responseData = getRequest(`/creator/database/list`, dbQueryParam, undefined);

                //如果请求成功
                if (200 === responseData.status) {
                    console.log("导入操作 查询 【数据库】列表的数据：", responseData);
                    this.databaseOptions = responseData.data;

                }
                //endregion


                // 获取数据库表的列表
                this.tableQueryParam = {
                    tableSchema: null,
                    tableName: null,
                    page: 1,
                    limit: 10,
                };
                this.handleTableListQuery();


                console.log("打开导入窗口");


            },

            //子级checkbox被选择
            childCheckboxOnClick(e) {


            },

            //生成数据表父级checkbox被选择
            genTableParentCheckboxOnClick(e) {
                let that = this;
                //如果被选中
                if (e.target.checked) {
                    that.genTablePagination.list.forEach((item) => {
                        // console.log("item ===", item);
                        that.selectGenTableIds.push(item.tableId);
                    });
                    return;
                }
                //清空选择的数据表id
                that.selectGenTableIds = [];

            },

            /**
             * 生成代码分页按键点击
             */
            genTablePaginationOnClick(flag = '') {
                let curPage = this.genTablePaginationQueryParam.page;

                let totalPage = this.genTablePagination.totalPage;

                if ('p' == flag) {
                    curPage = Math.max(1, curPage - 1);
                } else if ('n' == flag) {
                    curPage = Math.min(totalPage, curPage + 1);
                } else {
                    curPage = flag
                }
                this.genTablePaginationQueryParam.page = curPage;
                console.log("【代码生成列表】被点击的分页元素为：", this.genTablePaginationQueryParam.page);

                this.getGenTableList()

            },

            /**
             * 获取生成的数据表列表
             */
            getGenTableList() {


                //获取列表查询参数对象
                let queryParam = this.genTablePaginationQueryParam;

                let responseData = getRequest(`/creator/gen/list`, queryParam, undefined);
                console.log("【生成数据列表】响应数据为：", responseData);

                if (200 === responseData.status) {
                    //更新生成代码列表数据
                    this.genTablePagination.list = responseData.data;
                    let count = responseData.count;
                    //更新总记录数据
                    this.genTablePagination.totalCount = count;
                    let limit = queryParam.limit;
                    let totalPage = Math.ceil(count / limit);
                    //更新总页数
                    this.genTablePagination.totalPage = totalPage;


                    //region 计算页数列表


                    //当前页数
                    let currentPage = queryParam.page;


                    let startPage = 1, endPage = totalPage;


                    //如果总页数大于10
                    if (totalPage > 10) {
                        startPage = currentPage - 5 < 0 ? 1 : (currentPage - 4);
                        endPage = startPage + 9 > totalPage ? totalPage : (startPage + 9)


                        let offset = endPage - startPage;
                        if (offset != 9) {
                            startPage = endPage - 9;
                        }
                    }


                    let pageNumList = [];
                    for (let i = startPage; i <= endPage; i++) {
                        pageNumList.push(i);
                    }
                    this.genTablePagination.pageNumList = pageNumList;
                    //endregion


                }

            }


        }
        , created() {

            this.getGenTableList();

            console.log("table-list 的vue对象实例化完成！")
        }
    });


});